package com.kefu.chat.service;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.kefu.basic.mapper.BasicTagMapper;
import com.kefu.basic.model.BasicTag;
import com.kefu.chat.mapper.ChatSessionMapper;
import com.kefu.chat.mapper.ChatSessionTagRelMapper;
import com.kefu.chat.model.ChatSession;
import com.kefu.chat.model.ChatSessionTagRel;
import com.kefu.chat.vo.ChatSessionTagRelInsertVo;
import com.kefu.common.service.AbstractKefuService;
import com.kefu.common.util.Assert;
import com.kefu.common.util.JacksonUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Slf4j
@Service
public class ChatSessionTagRelService extends AbstractKefuService<ChatSessionTagRel> {
    @Resource
    private BasicTagMapper basicTagMapper;
    @Resource
    private ChatSessionMapper chatSessionMapper;
    @Resource
    private ChatSessionTagRelMapper chatSessionTagRelMapper;

    public ChatSession addTag(ChatSessionTagRelInsertVo chatSessionTagRelVo) {
        ChatSession session = chatSessionMapper.selectByPrimaryKey(chatSessionTagRelVo.getSessionId());
        Assert.isNull(session, "会话不存在！");
        chatSessionTagRelMapper.delete(Wrappers.lambdaQuery(ChatSessionTagRel.class)
                .eq(ChatSessionTagRel::getSessionId, chatSessionTagRelVo.getSessionId()));
        List<ChatSessionTagRel> chatSessionTagRels = chatSessionTagRelVo.tagConvert(chatSessionTagRelVo.getSessionId());
        if (CollUtil.isNotEmpty(chatSessionTagRels)) {
            save(chatSessionTagRels);
            List<BasicTag> basicTags = basicTagMapper.selectList(Wrappers.lambdaQuery(BasicTag.class)
                    .in(BasicTag::getTagId, chatSessionTagRelVo.getBasicTags()));
            session.setBasicTag(basicTags);
            log.info("批量保存客户会话标签信息:{}, {}", chatSessionTagRelVo, JacksonUtil.toString(session));
        }
        return session;
    }
}
